package com.xingkeduo.service.api.marketing.impl;

import java.util.Date;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xingkeduo.dao.TActivityCodeMapper;
import com.xingkeduo.dao.TActivityDaysMapper;
import com.xingkeduo.dao.TActivityMapper;
import com.xingkeduo.dao.TActivityMapperSpec;
import com.xingkeduo.dao.TActivityUseHistoryMapper;
import com.xingkeduo.dao.TMarketingCardMapper;
import com.xingkeduo.dao.TMarketingCouponBagMapper;
import com.xingkeduo.dao.TMarketingCouponMapper;
import com.xingkeduo.dao.TMarketingMapperSpec;
import com.xingkeduo.dao.TMarketingReceiveHistoryCardMapper;
import com.xingkeduo.dao.TMarketingReceiveHistoryCouponBagMapper;
import com.xingkeduo.dao.TMarketingReceiveHistoryCouponMapper;
import com.xingkeduo.dao.TMarketingReceiveHistoryMapperSpec;
import com.xingkeduo.dao.TMarketingUseHistoryCardMapper;
import com.xingkeduo.dao.TMarketingUseHistoryCouponMapper;
import com.xingkeduo.feign.ManageUserFeignService;
import com.xingkeduo.model.example.TActivityUseHistoryExample;
import com.xingkeduo.model.param.ActivityUseParam;
import com.xingkeduo.model.param.MarketingParam.MarketingRefundTypeEnum;
import com.xingkeduo.model.param.MarketingParam.MarketingTypeEnum;
import com.xingkeduo.model.param.MarketingReceiveHistoryParam.MarketingReceiveStatusEnum;
import com.xingkeduo.model.po.TActivity;
import com.xingkeduo.model.po.TActivityUseHistory;
import com.xingkeduo.model.po.TMarketingReceiveHistory;
import com.xingkeduo.model.po.TMarketingUseHistory;
import com.xingkeduo.model.po.TMarketingUseHistoryCard;
import com.xingkeduo.model.po.TMarketingUseHistoryCoupon;
import com.xingkeduo.service.api.marketing.UserConsumeService;
import com.xingkeduo.service.cms.marketing.InventoryService;
import com.xingkeduo.service.consume.UserService;
import com.xingkeduo.util.Constant;
import com.xingkeduo.util.tool.ResponseMessage;

@Service
public class UserConsumeServiceImpl implements UserConsumeService {
	Logger logger = LoggerFactory.getLogger(UserConsumeServiceImpl.class);

	@Autowired
	TActivityDaysMapper tActivityDaysMapper;
	@Autowired
	TActivityCodeMapper tActivityCodeMapper;
	@Autowired
	InventoryService inventoryService;
	@Autowired
	TMarketingMapperSpec tMarketingMapperSpec;
	@Autowired
	TMarketingReceiveHistoryMapperSpec tMarketingReceiveHistoryMapperSpec;
	@Autowired
	TActivityMapper tActivityMapper;
	@Autowired
	TActivityUseHistoryMapper tActivityUseHistoryMapper;
	@Autowired
	ManageUserFeignService manageUserFeignService;
	@Autowired
	TActivityMapperSpec tActivityMapperSpec;
	@Autowired
	TMarketingReceiveHistoryCardMapper tMarketingReceiveHistoryCardMapper;
	@Autowired
	TMarketingReceiveHistoryCouponMapper tMarketingReceiveHistoryCouponMapper;
	@Autowired
	TMarketingReceiveHistoryCouponBagMapper tMarketingReceiveHistoryCouponBagMapper;
	@Autowired
	TMarketingUseHistoryCouponMapper tMarketingUseHistoryCouponMapper;
	@Autowired
	TMarketingUseHistoryCardMapper tMarketingUseHistoryCardMapper;
	@Autowired
	TMarketingCouponMapper tMarketingCouponMapper;
	@Autowired
	TMarketingCardMapper tMarketingCardMapper;
	@Autowired
	TMarketingCouponBagMapper tMarketingCouponBagMapper;
	@Autowired
	UserService userService;
	@Override
	@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = 36000, rollbackFor = Exception.class)
	public ResponseMessage confirmOrder(ActivityUseParam activityUseParam) {
		buildUserAllUserIds(activityUseParam);
		if (activityUseParam.getMarketingReceiveHistoryId() != null) {
			TMarketingReceiveHistory history = selectMarketingReceiveHistoryByPrimaryKey(
					activityUseParam.getMarketingReceiveHistoryId(), activityUseParam.getMarketingType());
			// 状态验证
			if (history == null || MarketingReceiveStatusEnum.AVAILABLE.getCode() != history.getStatus().intValue()
					|| (!activityUseParam.getUserIdList().contains(history.getUserId()))) {
				logger.info("【下单】参数验证不通过:marketingReceiveHistoryId:{},userId:{},status:{},historyUserId:{},list:{}",
						activityUseParam.getMarketingReceiveHistoryId(), activityUseParam.getUserId(),
						history.getStatus(),history.getUserId(),JSON.toJSONString(activityUseParam.getUserIdList()));
				return ResponseMessage.error("当前券，卡不可用", 500);
			}
			Integer status = MarketingReceiveStatusEnum.AVAILABLE.getCode();
			if (history.getMarketingType().intValue() == MarketingTypeEnum.COUPON.getCode()) {
				status = MarketingReceiveStatusEnum.USED.getCode();
			}
			if (history.getInitUseLimit().intValue() != 0
					&& history.getInitUseLimit().intValue() - history.getCurrentUseLimit().intValue() <= 1) {
				status = MarketingReceiveStatusEnum.USED.getCode();
			}
			tMarketingReceiveHistoryMapperSpec.updateCurrentUseLimitById(history.getId(),
					activityUseParam.getMarketingType(), status, 1);
			// 新增券卡使用记录
			TMarketingUseHistory useHistory = new TMarketingUseHistory(activityUseParam.getMarketingReceiveHistoryId(),
					history.getMarketingBagId(), history.getMarketingId(), history.getMarketingType() + "",
					history.getServiceType(), history.getMarketingName(), activityUseParam.getOrderId(),
					activityUseParam.getUserId(), history.getCouponAmount(),
					activityUseParam.getReduceMarketingAmount(), activityUseParam.getAppointmentDate(), new Date(),
					Constant.STATUS_YES, activityUseParam.getStoreId(), activityUseParam.getStoreName(), "",
					activityUseParam.getHairStyleId());
			if (activityUseParam.getMarketingType().intValue() == MarketingTypeEnum.COUPON.getCode()) {
				TMarketingUseHistoryCoupon couponUseHistory = new TMarketingUseHistoryCoupon();
				BeanUtils.copyProperties(useHistory, couponUseHistory);
				tMarketingUseHistoryCouponMapper.insertSelective(couponUseHistory);
			} else if (activityUseParam.getMarketingType().intValue() == MarketingTypeEnum.CARD.getCode()) {
				TMarketingUseHistoryCard cardUseHistory = new TMarketingUseHistoryCard();
				BeanUtils.copyProperties(useHistory, cardUseHistory);
				tMarketingUseHistoryCardMapper.insertSelective(cardUseHistory);
			}
		}
		// 新增活动使用记录
		if (activityUseParam.getActivityId() != null) {
			TActivity activity = tActivityMapper.selectByPrimaryKey(activityUseParam.getActivityId());
			if (activity == null || MarketingReceiveStatusEnum.AVAILABLE.getCode() != activity.getStatus().intValue()) {
				logger.info("【下单】参数验证不通过:activityid:{},status:{}", activityUseParam.getActivityId(),
						activity.getStatus());
				return ResponseMessage.error("当前活动不可用", 500);
			}
			tActivityMapperSpec.deductCurrentUseLimitById(activity.getId(), 1);

			TActivityUseHistory useHistory = new TActivityUseHistory(activityUseParam.getActivityId(),
					activity.getActivityType(), activity.getActivityMode(), activity.getName(),
					activityUseParam.getOrderId(), activityUseParam.getUserId(), activity.getActivityAmount(),
					activityUseParam.getAppointmentDate(), new Date(), Constant.STATUS_YES,
					activityUseParam.getStoreId(), activityUseParam.getStoreName(), "",
					activityUseParam.getHairStyleId(), activityUseParam.getReduceActivityAmount());
			tActivityUseHistoryMapper.insertSelective(useHistory);
		}
		return ResponseMessage.ok("券，卡使用成功");
	}

	private TMarketingReceiveHistory selectMarketingReceiveHistoryByPrimaryKey(Long marketingReceiveHistoryId,
			Integer marketingType) {
		if (marketingType.intValue() == MarketingTypeEnum.COUPON.getCode()) {
			return tMarketingReceiveHistoryCouponMapper.selectByPrimaryKey(marketingReceiveHistoryId);
		} else if (marketingType.intValue() == MarketingTypeEnum.CARD.getCode()) {
			return tMarketingReceiveHistoryCardMapper.selectByPrimaryKey(marketingReceiveHistoryId);
		} else if (marketingType.intValue() == MarketingTypeEnum.COUPON_BAG.getCode()) {
			return tMarketingReceiveHistoryCouponBagMapper.selectByPrimaryKey(marketingReceiveHistoryId);
		}
		return null;
	}

	private void buildUserAllUserIds(ActivityUseParam param) {
		if (CollectionUtils.isEmpty(param.getUserIdList())) {
			List<Long> userList = userService.queryUserIdsByUserId(param.getUserId());
			param.setUserIdList(userList);		
		}
	}
	@Override
	@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = 36000, rollbackFor = Exception.class)
	public ResponseMessage refundOrder(ActivityUseParam activityUseParam) {
		buildUserAllUserIds(activityUseParam);
		if (activityUseParam.getMarketingReceiveHistoryId() != null) {
			TMarketingReceiveHistory history = selectMarketingReceiveHistoryByPrimaryKey(
					activityUseParam.getMarketingReceiveHistoryId(), activityUseParam.getMarketingType());
			if (history == null || (!activityUseParam.getUserIdList().contains(history.getUserId()))) {
				logger.info("【退款退单】参数验证不通过:marketingReceiveHistoryId:{},userId:{}",
						activityUseParam.getMarketingReceiveHistoryId(), activityUseParam.getUserId());
				return ResponseMessage.error("当前券,卡不可撤销", 500);
			}
			Integer status = MarketingReceiveStatusEnum.AVAILABLE.getCode();
			if (history.getRefundType().intValue() == MarketingRefundTypeEnum.RETURN_COUPON.getCode()) {
				tMarketingReceiveHistoryMapperSpec.updateCurrentUseLimitById(history.getId(),
						activityUseParam.getMarketingType(), status, -1);
			} else if(activityUseParam.getMarketingType().intValue()==MarketingTypeEnum.COUPON.getCode()){
				status = MarketingReceiveStatusEnum.REFUND_INVALID.getCode();
				tMarketingReceiveHistoryMapperSpec.updateCurrentUseLimitById(history.getId(),
						activityUseParam.getMarketingType(), status, 0);
			}
			// 新增券卡使用记录
			TMarketingUseHistory useHistory = new TMarketingUseHistory(activityUseParam.getMarketingReceiveHistoryId(),
					history.getMarketingBagId(), history.getMarketingId(), history.getMarketingType() + "",
					history.getServiceType(), history.getMarketingName(), activityUseParam.getOrderId(),
					activityUseParam.getUserId(), history.getCouponAmount(),
					activityUseParam.getReduceMarketingAmount(), activityUseParam.getAppointmentDate(), new Date(),
					Constant.STATUS_NO_2, activityUseParam.getStoreId(), activityUseParam.getStoreName(), "",
					activityUseParam.getHairStyleId());
			if (activityUseParam.getMarketingType().intValue() == MarketingTypeEnum.COUPON.getCode()) {
				TMarketingUseHistoryCoupon couponUseHistory = new TMarketingUseHistoryCoupon();
				BeanUtils.copyProperties(useHistory, couponUseHistory);
				tMarketingUseHistoryCouponMapper.insertSelective(couponUseHistory);
			} else if (activityUseParam.getMarketingType().intValue() == MarketingTypeEnum.CARD.getCode()) {
				TMarketingUseHistoryCard cardUseHistory = new TMarketingUseHistoryCard();
				BeanUtils.copyProperties(useHistory, cardUseHistory);
				tMarketingUseHistoryCardMapper.insertSelective(cardUseHistory);
			}
		}
		if (activityUseParam.getActivityId() != null) {
			tActivityMapperSpec.increaseCurrentUseLimitById(activityUseParam.getActivityId(), 1);

			TActivityUseHistoryExample example = new TActivityUseHistoryExample();
			example.createCriteria().andActivityIdEqualTo(activityUseParam.getActivityId())
					.andStatusEqualTo(Constant.STATUS_YES).andOrderIdEqualTo(activityUseParam.getOrderId());
			TActivityUseHistory record = new TActivityUseHistory();
			record.setStatus(Constant.STATUS_NO_2);
			tActivityUseHistoryMapper.updateByExampleSelective(record, example);
		}
		return ResponseMessage.ok("券，卡退单成功");
	}
}
